package com.wswy.wzcx.ui.user

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.View
import com.baidu.mobstat.IIgnoreAutoTrace
import com.blankj.utilcode.util.KeyboardUtils
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.ProgressDialogObserver
import com.che.libcommon.ui.NavTabController
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.UserMode
import com.wswy.wzcx.model.resp.CaptchaData
import com.wswy.wzcx.module.GlobalConfigManager
import com.wswy.wzcx.module.ScTimes
import com.wswy.wzcx.module.base.CBaseActivity
import com.wswy.wzcx.module.validator.IValidator
import com.wswy.wzcx.module.validator.ImgCaptchaValidator
import com.wswy.wzcx.module.validator.PassValidator
import com.wswy.wzcx.module.validator.TCaptchaValidator
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ITestValidator
import kotlinx.android.synthetic.main.activity_login_holder.*
import java.util.*

class LoginHolderActivity : CBaseActivity(), NavTabController.FragmentProvider,IIgnoreAutoTrace, ITestValidator {



    private companion object {

        private const val TAG = "LoginHolderActivity"

        private const val TAG_LOGIN_FRONTEND = "login_frontend"

        private const val TAG_LOGIN = "login"

        private const val TAG_REG = "reg"

        private const val TAG_PHONE_VERIFY = "phone_verify"

        private const val TAG_PASSWORD_VERIFY = "password_verify"

        private const val TAG_WX_BIND = "wx_bind_status"
    }


    private lateinit var navTabController: NavTabController

    private lateinit var loginHolderViewModel: LoginHolderViewModel

    private var mValidator: IValidator? = null

    private val stack=Stack<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login_holder)

        loginHolderViewModel = provideViewModel(LoginHolderViewModel::class.java)
        loginHolderViewModel.onCreate()
        loginHolderViewModel.watchWXLogin()

        navTabController = NavTabController(this,supportFragmentManager,R.id.fl_container,true)

        navTabController.setOnChangeCallback {
            stack.push(it)

            Log.e(TAG, " --> $stack");

        }
        navTabController.show(getFirstKey())


        initEvent()

        initViews()

        ScTimes.startLoginPage()
    }

    private fun getFirstKey():String{
        return if (loginHolderViewModel.oneKeyLogin) TAG_LOGIN_FRONTEND else TAG_LOGIN
    }

    private fun initViews(){
        img_close.setOnClickListener {


            if (stack.isEmpty() || navTabController.isShowing(getFirstKey()) || navTabController.isShowing(TAG_WX_BIND)){
                finish()
            }else{
                var tag = stack.pop()

                if (navTabController.isShowing(tag) && stack.isNotEmpty()){
                    tag = stack.pop()
                }

                if (loginHolderViewModel.oneKeyLogin && tag == TAG_LOGIN){
                    changeClose()
                }
                navTabController.show(tag)
            }

            //
        }
    }

    private fun initEvent(){

        //事件处理
        loginHolderViewModel.getClickEventLiveData().observe(this, Observer {
            when(it){
                LoginHolderViewModel.CLICK_LOGIN -> {
                    //changeBack()
                    navTabController.show(TAG_LOGIN)
                }
                LoginHolderViewModel.CLICK_REG -> {
                    //changeBack()
                    //注册
                    navTabController.show(TAG_REG)
                }

                LoginHolderViewModel.CLICK_REG_NEXT_VERIFY -> {
                    //注册手机号验证完成
                    navTabController.show(TAG_PHONE_VERIFY)
                }

                LoginHolderViewModel.CLICK_SMS_CODE_NEXT_STEP -> {
                    //验证码完成
                    navTabController.show(TAG_PASSWORD_VERIFY)

                }
                LoginHolderViewModel.CLICK_FORGET_PWD -> {
                    //忘记密码
                    navTabController.show(TAG_REG)
                }

                LoginHolderViewModel.CLICK_WECHAT_LOGIN -> {
                    //微信登录
                    loginHolderViewModel.startWechatLogin()
                }

                LoginHolderViewModel.CLICK_WX_BIND_SUCCESS -> {
                    //微信登录成功
                    navTabController.show(TAG_WX_BIND)
                }
                else -> null

            }



        })

        //用户登录
        loginHolderViewModel.getUserModeLiveData().observe(this, Observer {
            it?.run {
                Intent().run {
                    putExtra(Constants.EXTRA_DATA,it)
                    setResult(Activity.RESULT_OK,this)
                }
                finish()
            }

        })

        loginHolderViewModel.getWXLoginLiveData().observe(this, Observer {
            it?.let {
                //微信登录成功
                Log.e(TAG, " --> $it");
               doWechatLogin(it.code)
            }

        })

    }


    private fun doWechatLogin(code:String){
        Api.get().wechatLogin(code).subscribe(object : ProgressDialogObserver<UserMode>(this,null,"登录中，请稍后..."){
            override fun onApiResult(t: UserMode?) {
                t?.let {
                    sendClickEvent(StatisticsId.u_wechat_done)
                    loginHolderViewModel.setUserLogined(t)
                }
            }

            override fun onApiError(result: BaseResult<*>?) {
                if (result != null && result.statusCode == 104014){
                    //未绑定，提示绑定
                    loginHolderViewModel.stepState.wechatCode = code
                    navTabController.show(TAG_REG)
                }else{
                    sendClickEvent(StatisticsId.u_wechat_fail)
                    toastErrorMsg(result)
                }
            }

        })

    }

    private fun changeBack(){
        ObjectAnimator.ofFloat(img_close,View.ROTATION,90f,0f).run {
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    img_close.setImageResource(R.drawable.ic_back)
                }

            })

            duration = 150
            start()

        }
    }

    private fun changeClose(){

        ObjectAnimator.ofFloat(img_close,View.ROTATION,0f,90f).run {

            addListener(object : AnimatorListenerAdapter(){

                override fun onAnimationEnd(animation: Animator?) {
                    img_close.setImageResource(R.drawable.ic_closed)
                }

            })

            duration = 150
            start()

        }
    }


    override fun getFragment(tag: String?): Fragment {
        return when(tag){
            TAG_LOGIN_FRONTEND -> LoginFrontendFragment()

            TAG_LOGIN -> LoginFragment()

            TAG_REG -> RegisterFragment()

            TAG_PHONE_VERIFY -> PhoneVerifyFragment()

            TAG_PASSWORD_VERIFY -> PasswordVerifyFragment()

            TAG_WX_BIND -> BindStatusFragment()

            else -> LoginFrontendFragment()
        }
    }


    override fun onBackPressed() {

        if (stack.isEmpty() || navTabController.isShowing(getFirstKey()) || navTabController.isShowing(TAG_WX_BIND)){
            super.onBackPressed()
        }else{
            var tag = stack.pop()

            if (navTabController.isShowing(tag) && stack.isNotEmpty()){
               tag = stack.pop()
            }


            if (loginHolderViewModel.oneKeyLogin && tag == TAG_LOGIN){
                changeClose()
            }
            navTabController.show(tag)
        }

    }

    override fun getValidator(data:CaptchaData?): IValidator? {

        mValidator?.onDestroy()
        if (data?.isImgCaptcha() == true){

            return ImgCaptchaValidator(this,data).also {
                mValidator = it
            }
        }

        if(data?.isTCW() == true){
            return TCaptchaValidator(this).also {
                mValidator = it
            }
        }
        if (data?.isPass() == true){
            return PassValidator(data).also {
                mValidator = it
            }
        }
//        if (mValidator == null){
//            mValidator = TCaptchaValidator(this)
//        }
        return null
    }

    override fun destroy() {
        mValidator?.onDestroy()
    }

    override fun onDestroy() {
        super.onDestroy()
        destroy()
        KeyboardUtils.hideSoftInput(this)
    }
}